<?php
/**
 * Created by PhpStorm.
 * User: 煌煌
 * Date: 2020/11/4
 * Time: 10:43
 * Email:zenghuang19@163.com
 */

namespace App\Http\Controllers;


use App\Models\Article;
use App\Models\Product;
use App\Services\IndexService;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class NewsController extends Controller
{
    private $URL = null;

    public function __construct()
    {
        $this->URL = env('QINIUURL');
    }

    /**
     *  资讯列表
     * Author: 煌
     * Date: 2020/11/4
     * Time: 10:51
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Foundation\Application|\Illuminate\View\View
     */
    public function list()
    {
        $url = $this->URL;
        $seo = Redis::get('seo');

        $allModel          = Redis::get('Info');
        $data['all_model'] = json_decode($allModel, true);

        $data['seo'] = json_decode($seo, true);
        $data['url'] = $url;

        $where = [
            'is_release' => Article::RELEASE,
        ];

        $data['news'] = Article::query()
                                  ->where($where)
                                  ->select('title', 'image', 'description', 'created_at', 'real_pv', 'pv', 'id')
                                  ->orderBy('is_star', 'desc')
                                  ->orderBy('id', 'desc')
                                  ->paginate();

        $data['hot'] = Article::query()
                              ->where($where)
                              ->select('title', 'id')
                              ->orderBy('is_star', 'desc')
                              ->orderByDesc('pv')
                              ->offset(0)
                              ->limit(9)
                              ->get();

        foreach ($data['news'] as $item) {
            $item->pv = $item->real_pv + $item->pv;
        }

        $data['text'] = '资讯列表';

        return view('news.newsList', $data);
    }

    public function details(Request $request, $id)
    {
        $page   = $request->get('page', 1);
        $size   = $request->get('size', 10);
        $result['news'] = Article::query()->where('id', $id)->where([
            'is_release' => 1,
        ])->first([
            'title',
            'image',
            'details',
            'video',
            'video_cover',
            'real_pv',
            'pv',
            'created_at',
            'seo_title',
            'seo_description',
            'seo_keyword',
            'id',
            'author'
        ]);

        if ($result) {
            Article::where('id', $id)->increment('real_pv');
            $result['prev']           = $this::getNewsPrev($id);
            $result['next']           = $this::getNewsNext($id);
            $result['recommend_news'] = $this::getRecommendNewsList($page, $size, $request);

            $result['url']       = $this->URL;
            $allModel            = Redis::get('Info');
            $result['all_model'] = json_decode($allModel, true);
            $result['text']      = '资讯详情';
            IndexService::indexCache();

            return view('news.newsDesc', $result);
        } else {
            return redirect('/');
        }
    }

    /**
     * 推荐新闻
     *
     * @return array
     */
    protected function getRecommendNewsList($page, $size, $request)
    {
        $fields = ['id', 'title'];
        $total  = Article::query()->where(['is_star' => Article::RECOMMEND, 'is_release' => Article::RELEASE])->count();

        // 开始
        $start  = ($page - 1) * $size;
        $result = Article::query()
                               ->where(['is_star' => Article::RECOMMEND, 'is_release' => Article::RELEASE])
                               ->orderByDesc('pv')
                               ->orderByDesc('id')
                               ->offset($start)
                               ->limit($size)
                               ->get($fields);

        $result = new LengthAwarePaginator($result, $total, $size, $page,
            ['path' => env('APP_URL') . '/recommend/news', 'query' => $request->all()]);
        $result = $result->toArray();

        return $result;
    }

    /**
     * 上一条新闻
     *
     * @param int $id
     *
     * @return array
     */
    protected function getNewsPrev(int $id)
    {
        // 上一条新闻
        $prev = DB::select("select id,title from articles  where articles.id = (select min(id) from articles where id > " . $id . " and is_release = 1 order by is_star desc)");

        return $prev ? (array)$prev[0] : [];
    }

    /**
     * 下一条新闻
     *
     * @param int $id
     *
     * @return array
     */
    protected function getNewsNext(int $id)
    {
        // 下一条新闻
        $next = DB::select("select id,title from articles  where articles.id = (select max(id) from articles where id < " . $id . " and is_release = 1 order by is_star desc)");

        return $next ? (array)$next[0] : [];
    }
}
